#include "Mutex.hpp"
#include <unistd.h>
int ticket = 1000;
//pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
LockModule::Mutex mutex;//要把锁声明为全局的 要不在函数内每个线程都会拥有一把锁 达不到互斥的目的

void *rountime(void *args)
{
  //LockModule::Mutex mutex;
  char *name = (char *)args;
  while (true)
  {
    
    //pthread_mutex_lock(&mutex);
    mutex.Lock();
    if (ticket > 0)
    {
      usleep(1000);//不加锁会有线程同时访问一份公共资源的问题 导致ticket被减到负数
      ticket--;
      printf("%s get ticket %d \n", name, ticket);
      //pthread_mutex_unlock(&mutex);
      mutex.Unlock();
    }
    else
    {
      //pthread_mutex_unlock(&mutex);

      mutex.Unlock();
      break;
    }  
    
    
  }
  return nullptr;
}

int main()
{
  pthread_t tid1, tid2, tid3, tid4;
  pthread_create(&tid1, nullptr, rountime, (void *)"thread-1");
  pthread_create(&tid2, nullptr, rountime, (void *)"thread-2");
  pthread_create(&tid3, nullptr, rountime, (void *)"thread-3");
  pthread_create(&tid4, nullptr, rountime, (void *)"thread-4");
  
  pthread_join(tid1,nullptr);
  pthread_join(tid2,nullptr);
  pthread_join(tid3,nullptr);
  pthread_join(tid4,nullptr);
  printf("线程全部回收\n");
  return 0;
}
